<template>
  <div class="w-1/2">
    <van-field
      v-model="pickVal"
      label="公司简称："
      placeholder="选择公司"
      :readonly="true"
      @click="isShowPop = true"
    />
    <van-popup v-model:show="isShowPop" position="bottom" round>
      <van-search
        v-model="searchValue"
        shape="round"
        placeholder="请输入搜索关键词"
        @update:model-value="onSearch"
      />
      <van-picker :columns="selectList" @confirm="onConfirm" @cancel="onCancel" />
    </van-popup>
  </div>
</template>

<script setup>
const pickVal = defineModel()
const props = defineProps({
  // 传入的list必须是响应式数组，而且初始值为空
  list: {
    type: Array,
    required: true
  }
})
// 搜索列表
const selectList = ref([])
watch(
  () => props.list,
  (val) => {
    selectList.value = JSON.parse(JSON.stringify(val))
  }
)

// 是否显示客户单位popup
const isShowPop = ref(false)
// 搜索关键字
const searchValue = ref('')
// 搜索
const onSearch = (search) => {
  // console.log(search)
  if (search === '') {
    // 清空搜索关键字后，获取所有的内容
    selectList.value = props.list
  } else {
    selectList.value = props.list.filter((item) => {
      return item.text.includes(search)
    })
  }
}
// 确认后，给表单添加上选的值
const onConfirm = async (option) => {
  console.log(option)
  pickVal.value = option.selectedOptions[0]?.text
  isShowPop.value = false
}
// 关闭弹窗
const onCancel = () => {
  isShowPop.value = false
}
</script>

<style lang="scss" scoped>
:deep(.van-cell__title.van-field__label) {
  width: 4.5rem !important;
  margin-right: 0 !important;
}
</style>
